<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme

export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    unit: {
      type: String,
      default: "台",
    },
    dataName: {
      type: String,
      default: "容量",
    },
    zglD: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
      dataList: [120, 200, 150, 80, 70, 110, 130],
    };
  },
  watch: {
    zglD: {
      handler() {
        this.initChart();
      },
      deep: true
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");

      // 拆分数据
      const splitData = {
        name: this.zglD.map(item => item.name),
        zgl: this.zglD.map(item => item.zgl)
      };

      this.chart.setOption({
        legend: {
          textStyle: {
            color: "#ffffff",
          },
          right: 0,
          itemHeight: 5,
          itemWidth: 20,
          backgroundColor: "#0AA7FF4D",
        },
        grid: {
          top: 30,
          left: 40,
          right: 0,
          bottom: 30,
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: "category",
          data: splitData.name,
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          splitLine: {
            lineStyle: {
              type: "dashed",
              color: "#B0D7FF33",
            },
          },
          name: `单位：${this.unit}`,
          nameTextStyle: {
            color: "#999999",
          },
        },
        series: [
          {
            name: `${this.dataName}`,
            data: splitData.zgl,
            barWidth: 20,
            type: "bar",
            itemStyle: {
              color: "#1978E5",
            },
            showBackground: true,
            backgroundStyle: {
              color: "#0AA7FF1A",
            },
          },
        ],
      });
    },
  },
};
</script>
